﻿namespace Tools.Android
{
    public partial class MySqlConnectForm : Form
    {

        private List<ConnectionInfo> _connections;
        private ConnectionInfo _currentConnection;


        public MySqlConnectForm()
        {
            InitializeComponent();
            _connections = new List<ConnectionInfo>();
        }


        /// <summary>
        /// 测试完成后，确认连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_test_Click(object sender, EventArgs e)
        {
            if (ValidateInput())
            {
                var connectionInfo = GetConnectionInfoFromInput();
                string errorMessage;

                // 显示加载状态
                btn_test.Enabled = false;
                btn_test.Text = "测试中...";
                this.Cursor = Cursors.WaitCursor;

                try
                {
                    bool success = MySQLHelper.TestConnection(connectionInfo, out errorMessage);

                    if (success)
                    {
                        MessageBox.Show("连接测试成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        _currentConnection = connectionInfo;
                        btn_submit.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show($"连接测试失败: {errorMessage}", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        btn_submit.Enabled = false;
                    }
                }
                finally
                {
                    // 恢复状态
                    btn_test.Enabled = true;
                    btn_test.Text = "测试连接";
                    this.Cursor = Cursors.Default;
                }
            }
        }


        /// <summary>
        /// 数据库连接测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_submit_Click(object sender, EventArgs e)
        {
            if (_currentConnection == null)
            {
                MessageBox.Show("请先进行连接测试并确保测试成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 检查连接名称是否已存在
            if (ConfigHelper.ConnectionNameExists(_currentConnection.ConnectionName))
            {
                DialogResult result = MessageBox.Show(
                    "该连接名称已存在，是否覆盖？",
                    "确认",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                if (result == DialogResult.No)
                {
                    return;
                }
                // 移除已存在的连接
                _connections.RemoveAll(c => c.ConnectionName.Equals(_currentConnection.ConnectionName, StringComparison.OrdinalIgnoreCase));
            }

            // 添加新连接并保存
            _connections.Add(_currentConnection);
            try
            {
                ConfigHelper.SaveConnections(_connections);
                MessageBox.Show("连接信息保存成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存连接失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }




        #region 输入验证

        // 验证输入是否有效
        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(txt_title.Text))
            {
                MessageBox.Show("请输入连接名称", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txt_title.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txt_host.Text))
            {
                MessageBox.Show("请输入服务器地址", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txt_host.Focus();
                return false;
            }

            if (!int.TryParse(txt_port.Text.Trim(), out int port) || port <= 0 || port > 65535)
            {
                MessageBox.Show("请输入有效的端口号（1-65535）", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txt_port.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txt_database.Text))
            {
                MessageBox.Show("请输入数据库名称", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txt_database.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txt_pwd.Text))
            {
                MessageBox.Show("请输入数据库密码", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txt_pwd.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txt_name.Text))
            {
                MessageBox.Show("请输入用户名", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txt_name.Focus();
                return false;
            }

            return true;
        }

        #endregion

        #region 从输入控件中获取连接信息
        // 从输入控件获取连接信息
        private ConnectionInfo GetConnectionInfoFromInput()
        {
            return new ConnectionInfo
            {
                ConnectionName = txt_title.Text.Trim(),
                Server = txt_host.Text.Trim(),
                Port = int.TryParse(txt_port.Text.Trim(), out int port) ? port : 3306,
                Database = txt_database.Text.Trim(),
                Username = txt_name.Text.Trim(),
                Password = txt_pwd.Text
            };
        }
        #endregion
    }
}
